package com.wuxiaofan.api;

import com.wuxiaofan.entity.User;
import com.wuxiaofan.service.GoodsService;
import com.wuxiaofan.vo.GoodsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@Slf4j
public class GoApi {

    @Resource
    private GoodsService goodsService;

    @RequestMapping("/index")
    public String goToIndex(long userId, Model model) {
        model.addAttribute("userId", userId);
        return "index";
    }

    @RequestMapping("/goToLogin")
    public String goToLogin() {
        return "login";
    }

    @RequestMapping("/goToGoodsList")
    public String goToGoodsList(HttpSession session, @CookieValue("ticket") String ticket, Model model) {
        User user = (User)session.getAttribute(ticket);
        log.info("user:{}", user);
        if (user == null) {
            return "login";
        }
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.list());
        return "goodsList";
    }

    @RequestMapping("/goToGoodsDetail")
    public String goToGoodsDetail(HttpSession session, @CookieValue("ticket") String ticket, long goodsId,
        Model model) {
        User user = (User)session.getAttribute(ticket);
        log.info("user:{}", user);
        if (user == null) {
            return "login";
        }
        model.addAttribute("user", user);
        int seckillStatus = 0;
        GoodsVO detail = goodsService.detail(goodsId);
        if (detail.getEndDate().before(new Date())) {
            seckillStatus = 2;
            detail.setSecondNum(-1);
        } else if (detail.getStartDate().before(new Date())) {
            seckillStatus = 1;
        } else {
            long secondNum = (detail.getStartDate().getTime() - new Date().getTime()) / 1000;
            detail.setSecondNum(secondNum);
        }
        detail.setSeckillStatus(seckillStatus);
        model.addAttribute("goodsDetail", detail);
        return "goodsDetail";
    }

}
